package com.demo.rydemo.d_role_user.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.demo.rydemo.d_role_user.entity.DRoleUser;
import com.demo.rydemo.d_role_user.service.IDRoleUserService;
import com.demo.rydemo.d_role_user.vo.DRoleUserVO;
import com.demo.rydemo.d_user.entity.DUser;
import com.demo.rydemo.d_user.service.IDUserService;
import com.demo.rydemo.result.AjaxResult;
import com.demo.rydemo.result.CoreController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ry
 * @since 2020-08-27
 */
@Api(tags = "角色用户相关接口")
@RestController
@RequestMapping("/d_role_user/d-role-user")
public class DRoleUserController extends CoreController {

    @Autowired
    IDRoleUserService idRoleUserService;

    @Autowired
    IDUserService idUserService;

    @Autowired
    AjaxResult ajaxResult;


    @ApiOperation("通过角色账号查询到关联用户")
    @GetMapping("/getUserRoleByAccount")
    AjaxResult getUserRoleById(String roleId){
        QueryWrapper<DUser> queryWrapper = new QueryWrapper();
        queryWrapper.inSql("user_account"
                ,"select user_account  from d_role_user where role_id='"+roleId+"'");
        return ajaxResult.success(idUserService.list(queryWrapper));

    }


    @ApiOperation("批量添加角色关联用户")
    @PostMapping("/addRoleUsers")
    AjaxResult addRoleUsers(@RequestBody DRoleUserVO dRoleUserVO){
        List<DRoleUser> dRoleUsers = new ArrayList<>();
        for (int i = 0; i < dRoleUserVO.getUserIds().length; i++){
            DRoleUser dRoleUser = new DRoleUser();
            dRoleUser.setRoleUserId(UUID.randomUUID().toString().replace("-",""));
            dRoleUser.setRoleId(dRoleUserVO.getRoleId());
            dRoleUser.setCreateTime(new Date());
            dRoleUser.setUserId(dRoleUserVO.getUserIds()[i]);
            dRoleUsers.add(dRoleUser);
        }
        Boolean flag = false;
        flag = idRoleUserService.saveBatch(dRoleUsers);
        if(flag){
            return ajaxResult.success("批量添加成功");
        }
        return ajaxResult.error("批量添加失败,请联系管理员");
    }
}
